package com.hyving.home.mybatismulti.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@MapperScan(
        // 指定该数据源扫描指定包下面的Mapper接口文件
        basePackages = "com.hyving.home.mybatismulti.repository.second.mapper",
        sqlSessionFactoryRef = "sqlSessionFactorySecond",
        sqlSessionTemplateRef = "sqlSessionTemplateSecond")
public class SecondDataSourceConfig {

    // 注入数据源1
    @Resource
    @Qualifier("secondDataSource")
    private DataSource secondDataSource;


    @Bean("dataSourceTransactionManagerSecond")
    public DataSourceTransactionManager dataSourceTransactionManagerSecond(@Qualifier("secondDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean("sqlSessionFactorySecond")
    public SqlSessionFactory sqlSessionFactorySecond() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(secondDataSource);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("sqlSessionTemplateSecond")
    public SqlSessionTemplate sqlSessionTemplateSecond() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactorySecond());
    }





}
